package com.seestech.sell.service.impl;


import com.seestech.sell.common.utils.IdGen;
import com.seestech.sell.common.exceptions.MyException;
import com.seestech.sell.domain.mapper.IRoleMenuDao;
import com.seestech.sell.domain.model.Role;
import com.seestech.sell.domain.model.RoleMenu;
import com.seestech.sell.domain.mapper.IRoleDao;
import com.seestech.sell.service.IRoleService;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * Created by idiot on 2016/12/13.
 */
@Service
public class RoleServiceImpl implements IRoleService {
    private static Logger logger = LoggerFactory.getLogger(RoleServiceImpl.class);
    @Resource
    private IRoleDao roleDao;
    @Resource
    private IRoleMenuDao roleMenuDao;

    @Override
    public List<Role> getAllRoles(RowBounds rowBounds, Role role) {
        return roleDao.getAllRoles(rowBounds, role);
    }

    @Override
    public void insert(Role info) {
        if(info.getRoleId() == null)
            info.setRoleId(IdGen.get().nextId());   //设置roleId
        if(info.getCreateTime() == null)
            info.setCreateTime(new Date());
        if(roleDao.insert(info) < 1){
            throw new MyException("新增角色失败");
        }
    }

    @Override
    public void update(Role info) {
        if(info.getUpdateTime() == null)
            info.setUpdateTime(new Date());
        if(roleDao.update(info) < 1){
            throw new MyException("修改角色失败");
        }
    }

    @Override
    public Role getRoleByRoleId(long roleId) {
        return roleDao.getRoleByRoleId(roleId);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void delete(long roleId) {
        //删除角色信息   以及绑定的角色菜单信息
        if(roleDao.delete(roleId) < 1){
            logger.error("删除角色信息失败");
        }
        //查询该角色所拥有的菜单
        List<RoleMenu> list = roleMenuDao.getRoleMenusByRoleId(roleId);
        if(list != null && list.size() > 0) {
            if (roleMenuDao.deleteRoleMenusByRoleId(roleId) < 1) {
                logger.error("删除角色菜单关系信息失败");
            }
        }
    }

    @Override
    public List<Role> getRolesByUserId(Long userId) {
        return roleDao.getRolesByUserId(userId);
    }

    @Override
    public List<Role> getAllValidRoles() {
        return roleDao.getAllValidRoles();
    }

}
